<?php
session_start();
/* 处理用户登录，
    业务逻辑：
    1.获取登录表单上的用户信息
    2.调用数据层的相应方法：get_user()
    3.登录成功跳转到index.php，失败跳转到error.php
*/
require "../model/userDao.php";
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    edit_user_state($_SESSION['uid'], 0);
    // 清除session并跳转
    session_destroy();
    header("Location: ../views/login.php");
    exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取登录表单上的用户信息
    $uname = $_POST['uName'];
    $upass = $_POST['uPass'];
    // 调用get_user()
    $result = get_user($uname, $upass);
    // 判断登录是否成功
    if (count($result) > 0) {
        # 登录成功
        # 登录成功后修改state状态为1   
        edit_user_state($result['uId'], 1);
        $_SESSION['uid'] = $result['uId'];
        $_SESSION['username'] = $result['uName'];
        $_SESSION['userid'] = $result['uId'];
        $_SESSION['head'] = $result['head'];
        $_SESSION['state'] = $result['state'];
        $_SESSION['role'] = $result['role'];
        # 跳转到判断是用户还是管理员
        if ($result['role'] === 'user') {
            header("location:../views/index.php");
        } else {
            header("location:../../bms/views/indexBms.php");
        }
    } else {
        # 登录失败，跳转到error.php
        header("location:../views/login.php?error=用户名或密码错误");
    }

} else {
    header("location:../views/error.php?msg=非法访问");
}
?>